Component({
  data: {
    selected: 0,
    tabBarHeight: 0,
    isDark: false,
    list: [
      {
        pagePath: '/pages/index/index',
        text: '首页',
        iconPath: '/images/home.png',
        selectedIconPath: '/images/home_active.png'
      },
      {
        pagePath: '/pages/scan/scan',
        text: '扫一扫',
        iconPath: '/images/scan.png',
        selectedIconPath: '/images/scan_active.png'
      },
      {
        pagePath: '/pages/profile/profile',
        text: '个人中心',
        iconPath: '/images/profile.png',
        selectedIconPath: '/images/profile_active.png',
        dot: false  // 小红点
      }
    ]
  },

  lifetimes: {
    // 在组件实例进入页面节点树时执行
    attached() {
      // 1. 计算高度（rpx → px）
      const sys = wx.getSystemInfoSync();
      const rpx2px = sys.windowWidth / 750;
      this.setData({ tabBarHeight: 160 * rpx2px });

      // 2. 监听主题切换
      this.updateDarkMode(sys.theme);
      wx.onThemeChange?.(res => this.updateDarkMode(res.theme));

      // 3. 根据当前路由设置选中态，避免状态不同步
      try {
        const pages = getCurrentPages();
        const cur = pages[pages.length - 1];
        const route = '/' + (cur?.route || '');
        const idx = this.data.list.findIndex(i => i.pagePath === route);
        if (idx >= 0 && idx !== this.data.selected) {
          this.setData({ selected: idx });
        }
      } catch (e) {}
    }
  },

  methods: {
    updateDarkMode(theme) {
      this.setData({ isDark: theme === 'dark' });
    },

    switchTab(e) {
      const { path, index } = e.currentTarget.dataset;
      if (!path) return;
      // 使用 switchTab 跳转 tabBar 页，避免重复入栈
      wx.switchTab({ url: path });
      this.setData({ selected: Number(index) });
    },

    // 中间凸起按钮点击
    goCenter() {
      const path = this.data.list[1]?.pagePath;
      if (path) {
        // 使用 switchTab 跳转 tabBar 页，避免重复入栈
        wx.switchTab({ url: path });
        this.setData({ selected: 1 });
      }
    },

    /* 暴露给外部页面调用的接口 */
    setBadge(index, num) {
      const key = `list[${index}].badge`;
      this.setData({ [key]: num });
    },
    setDot(index, show) {
      const key = `list[${index}].dot`;
      this.setData({ [key]: show });
    }
  }
});